import React, { useEffect, useRef, useState } from 'react'
import { message } from 'antd'
import {
  CopyOutlined,
  ScissorOutlined,
  SnippetsOutlined,
  FireOutlined,
  EditOutlined,
  CompressOutlined
} from '@ant-design/icons'
import './styles.css'

export interface ContextMenuItem {
  key: string
  label: string
  icon?: React.ReactNode
  onClick: () => void
  disabled?: boolean
  divider?: boolean
}

export interface ContextMenuProps {
  /** 是否显示菜单 */
  visible: boolean
  /** 菜单位置 */
  position: { x: number; y: number }
  /** 菜单项列表 */
  items: ContextMenuItem[]
  /** 关闭回调 */
  onClose: () => void
}

/**
 * 右键上下文菜单组件
 * 用于在编辑器中提供右键菜单功能
 */
export const ContextMenu: React.FC<ContextMenuProps> = ({
  visible,
  position,
  items,
  onClose
}) => {
  const menuRef = useRef<HTMLDivElement>(null)
  const [adjustedPosition, setAdjustedPosition] = useState(position)

  // 点击外部关闭菜单
  useEffect(() => {
    if (!visible) return

    const handleClickOutside = (e: MouseEvent) => {
      if (menuRef.current && !menuRef.current.contains(e.target as Node)) {
        onClose()
      }
    }

    // 延迟添加监听器，避免立即触发
    const timer = setTimeout(() => {
      document.addEventListener('mousedown', handleClickOutside)
    }, 100)

    return () => {
      clearTimeout(timer)
      document.removeEventListener('mousedown', handleClickOutside)
    }
  }, [visible, onClose])

  // 调整菜单位置，防止超出屏幕
  useEffect(() => {
    if (!visible || !menuRef.current) return

    const menu = menuRef.current
    const menuRect = menu.getBoundingClientRect()
    const viewportWidth = window.innerWidth
    const viewportHeight = window.innerHeight

    let { x, y } = position

    // 右侧超出屏幕，向左调整
    if (x + menuRect.width > viewportWidth) {
      x = viewportWidth - menuRect.width - 10
    }

    // 底部超出屏幕，向上调整
    if (y + menuRect.height > viewportHeight) {
      y = viewportHeight - menuRect.height - 10
    }

    // 确保不超出左边和顶部
    x = Math.max(10, x)
    y = Math.max(10, y)

    setAdjustedPosition({ x, y })
  }, [visible, position])

  // 处理菜单项点击
  const handleItemClick = (item: ContextMenuItem) => {
    if (item.disabled) return
    item.onClick()
    onClose()
  }

  // 处理键盘事件
  useEffect(() => {
    if (!visible) return

    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        onClose()
      }
    }

    document.addEventListener('keydown', handleKeyDown)
    return () => document.removeEventListener('keydown', handleKeyDown)
  }, [visible, onClose])

  if (!visible) return null

  return (
    <div
      ref={menuRef}
      className="context-menu"
      style={{
        left: `${adjustedPosition.x}px`,
        top: `${adjustedPosition.y}px`
      }}
    >
      {items.map((item, index) => (
        <React.Fragment key={item.key}>
          {item.divider ? (
            <div className="context-menu-divider" />
          ) : (
            <div
              className={`context-menu-item ${item.disabled ? 'disabled' : ''}`}
              onClick={() => handleItemClick(item)}
            >
              {item.icon && <span className="context-menu-icon">{item.icon}</span>}
              <span className="context-menu-label">{item.label}</span>
            </div>
          )}
        </React.Fragment>
      ))}
    </div>
  )
}

/**
 * 创建编辑器默认右键菜单项
 */
export const createEditorContextMenuItems = (params: {
  hasSelection: boolean
  onCopy?: () => void
  onCut?: () => void
  onPaste?: () => void
  onSparkPrompt?: () => void
  onContinueWriting?: () => void
  onSummarize?: () => void
}): ContextMenuItem[] => {
  const { hasSelection, onCopy, onCut, onPaste, onSparkPrompt, onContinueWriting, onSummarize } = params

  return [
    {
      key: 'spark-prompt',
      label: '星星之火',
      icon: <FireOutlined />,
      onClick: () => {
        if (onSparkPrompt) {
          onSparkPrompt()
        } else {
          message.info('请先选中文字')
        }
      },
      disabled: !hasSelection
    },
    {
      key: 'divider-1',
      label: '',
      divider: true,
      onClick: () => {}
    },
    {
      key: 'continue-writing',
      label: '续写',
      icon: <EditOutlined />,
      onClick: () => {
        if (onContinueWriting) {
          onContinueWriting()
        }
      },
      disabled: !hasSelection
    },
    {
      key: 'summarize',
      label: '缩写',
      icon: <CompressOutlined />,
      onClick: () => {
        if (onSummarize) {
          onSummarize()
        }
      },
      disabled: !hasSelection
    },
    {
      key: 'divider-2',
      label: '',
      divider: true,
      onClick: () => {}
    },
    {
      key: 'copy',
      label: '复制',
      icon: <CopyOutlined />,
      onClick: () => {
        if (onCopy) {
          onCopy()
        } else {
          document.execCommand('copy')
          message.success('已复制', 1)
        }
      },
      disabled: !hasSelection
    },
    {
      key: 'cut',
      label: '剪切',
      icon: <ScissorOutlined />,
      onClick: () => {
        if (onCut) {
          onCut()
        } else {
          document.execCommand('cut')
          message.success('已剪切', 1)
        }
      },
      disabled: !hasSelection
    },
    {
      key: 'paste',
      label: '粘贴',
      icon: <SnippetsOutlined />,
      onClick: async () => {
        if (onPaste) {
          onPaste()
        } else {
          try {
            const text = await navigator.clipboard.readText()
            document.execCommand('insertText', false, text)
            message.success('已粘贴', 1)
          } catch (err) {
            message.error('粘贴失败，请使用Ctrl+V或Cmd+V')
          }
        }
      }
    }
  ]
}

export default ContextMenu
